package cn.itcast.bos.service.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.constant.Constants;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.domain.take_delivery.Order;
import cn.itcast.bos.domain.take_delivery.WorkBill;
import cn.itcast.bos.repository.AreaRepository;
import cn.itcast.bos.repository.FixedAreaRepository;
import cn.itcast.bos.repository.OrderRepository;
import cn.itcast.bos.repository.WorkBillRepository;
import cn.itcast.bos.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private FixedAreaRepository fixedAreaRepository;
	@Autowired
	private AreaRepository areaRepository;
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	@Autowired
	private WorkBillRepository workBillRepository;

	@Override
	public void saveOrder(Order order) {
		// 生成订单号
		order.setOrderNum(UUID.randomUUID().toString().replace("-", ""));
		// 下单时间
		order.setOrderTime(new Date());
		// 设置订单状态 1 待取件 2 运输中 3 已签收 4 异常
		order.setStatus("1");
		// 将sendArea和recArea由瞬时态变为持久态
		Area sendArea = order.getSendArea();
		Area persistSendArea = areaRepository.findByProvinceAndCityAndDistrict(sendArea.getProvince(),
				sendArea.getCity(), sendArea.getDistrict());
		Area recArea = order.getRecArea();
		Area persistRecArea = areaRepository.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());
		order.setSendArea(persistSendArea);
		order.setRecArea(persistRecArea);

		// 自动分单逻辑1，根据完全匹配的地址信息查询客户所在定区id，再关联该定区快递员
		String fixedAreaId = WebClient
				.create(Constants.CRM_MANAGEMENT_URL
						+ "/services/customerService/customer/findFixedAreaIdByAddressAndCustomerId?address="
						+ order.getSendAddress() + "&customerId=" + order.getCustomer_id())
				.type(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON).get(String.class);
		if (fixedAreaId != null) {
			// 根据定区id查找定区
			FixedArea fixedArea = fixedAreaRepository.findOne(fixedAreaId);
			// 根据定区查询该定区的所有快递员
			Iterator<Courier> iterator = fixedArea.getCouriers().iterator();
			while (iterator.hasNext()) {
				Courier courier = iterator.next();
				if (courier != null) {
					// 设置自动分单
					System.out.println("自动分单成功....");
					save(order, courier);
					//生成工单
					generateWorkBill(order);
					return;
				}
			}
		}
		// 自动分单逻辑2，根据分区关键字匹配自动分单
		for (SubArea subArea : persistSendArea.getSubareas()) {
			// 当前客户下单地址是否含有分区关键字4
			if (order.getSendAddress().contains(subArea.getKeyWords())) {
				// 找到分区，找到定区，找到快递员
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				while (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 设置自动分单
						System.out.println("自动分单成功....");
						save(order, courier);
						//生成工单
						generateWorkBill(order);
						return;
					}
				}
			}
		}

		for (SubArea subArea : persistSendArea.getSubareas()) {
			if (order.getSendAddress().contains(subArea.getAssistKeyWords())) {
				Iterator<Courier> iterator = subArea.getFixedArea().getCouriers().iterator();
				while (iterator.hasNext()) {
					Courier courier = iterator.next();
					if (courier != null) {
						// 设置自动分单
						System.out.println("自动分单成功....");
						save(order, courier);
						//生成工单
						generateWorkBill(order);
						return;
					}
				}
			}
		}
		// 进入人工分单
		order.setOrderType("2");
		orderRepository.save(order);
	}

	// 生成工单，发送短信给快递员
	public void generateWorkBill(final Order order) {
		// 生成工单
		WorkBill workBill = new WorkBill();
		workBill.setType("新");// 工单类型 新,追,销
		workBill.setPickstate("新单");// 取件状态
		workBill.setBuildtime(new Date());// 工单生成时间
		workBill.setRemark(order.getRemark());// 订单备注
		final String smsNumber = RandomStringUtils.randomNumeric(4);// 生成短信序号，用于发送短信
		workBill.setSmsNumber(smsNumber); // 短信序号
		workBill.setOrder(order);// 工单关联订单
		workBill.setCourier(order.getCourier());// 工单关联快递员
		workBillRepository.save(workBill);// 保存工单。
		// 发送信息
		jmsTemplate.send("bos_couriers", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", order.getCourier().getTelephone());// 快递员电话
				mapMessage.setString("num", smsNumber);// 验证码
				mapMessage.setString("sendAddres", order.getSendAddress());// 寄件地址
				mapMessage.setString("sendName", order.getSendName()); // 寄件人
				mapMessage.setString("sendMobile", order.getSendMobile()); // 寄件人电话
				mapMessage.setString("sendMobileMsg", order.getSendMobileMsg()); // 快递员稍话

				return mapMessage;
			}
		});
		// 发送短信成功，pickstate设置为“已通知”
		workBill.setPickstate("已通知");

		workBillRepository.save(workBill);

	}

	private void save(Order order, Courier courier) {
		// 将快递员关联订单
		order.setCourier(courier);
		// 设置分单的方式
		order.setOrderType("1");
		orderRepository.save(order);
	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return orderRepository.findByOrderNum(orderNum);
	}

}
